package com.ftg.learn.day15.myframework.proxy;

import com.ftg.learn.day15.myframework.DeptMapper;
import com.ftg.learn.day15.myframework.annotation.DeleteForMyself;
import com.ftg.learn.day15.myframework.annotation.InsertForMyself;
import com.ftg.learn.day15.myframework.annotation.SelectForMyself;
import com.ftg.learn.day15.myframework.annotation.UpdateForMyself;
import com.ftg.learn.day15.myframework.util.JdbcUtil;
import org.apache.ibatis.binding.MapperProxyFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 代理，为你的mapper生成一个实现类
 *
 * @author 布衣
 */
public class SqlMapperProxy {

    private static JdbcUtil jdbc = new JdbcUtil("root", "123456", "jdbc:mysql://localhost:3306/db2402");

    /**
     * 是不是就是为了生成一个mapper的实现类方法
     *
     * @param mapper 映射器
     * @param <T>    Class<T> 关联对象</T>
     * @return T
     */
    public static <T> T getMapper(Class<T> mapper) {
        return (T) Proxy.newProxyInstance(mapper.getClassLoader(), new Class[]{
                mapper
        }, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                SelectForMyself select = method.getAnnotation(SelectForMyself.class);
                if (select != null) {
                    String sql = select.value();

                    return jdbc.query(sql,args);
                }
                InsertForMyself insert = method.getAnnotation(InsertForMyself.class);
                UpdateForMyself update = method.getAnnotation(UpdateForMyself.class);
                DeleteForMyself delete = method.getAnnotation(DeleteForMyself.class);
                if (insert != null || update != null || delete != null) {
                    String sql = insert.value();
                    return jdbc.dml(sql, args);
                }
                return null;
            }
        });
    }

    public static void main(String[] args) {
        DeptMapper deptMapper = getMapper(DeptMapper.class);

        int num = deptMapper.insert(99, "测试", "测试");
        System.out.println(num);


        List<Map<String, Object>> maps = deptMapper.showAll1("abc");
        maps.forEach(System.out::println);

    }

}
